from flask import jsonify, request
from extensions import db
from models.project import Project
from . import api
from .errors import bad_request, not_found
from utils.logger import logger, log_api_call

@api.route('/projects', methods=['GET'])
@log_api_call
def get_projects():
    """获取所有项目列表"""
    logger.info("获取项目列表")
    projects = Project.query.all()
    logger.info(f"找到 {len(projects)} 个项目")
    return jsonify([project.to_dict() for project in projects])

@api.route('/projects/<int:id>', methods=['GET'])
@log_api_call
def get_project(id):
    """获取单个项目详情"""
    logger.info(f"获取项目详情: {id}")
    project = Project.query.get_or_404(id)
    logger.info(f"找到项目: {project.name}")
    return jsonify(project.to_dict())

@api.route('/projects', methods=['POST'])
@log_api_call
def create_project():
    """创建新项目"""
    logger.info("开始处理创建项目请求")
    
    if not request.is_json:
        logger.warning("请求Content-Type不是application/json")
        return bad_request('Content-Type must be application/json')
    
    try:
        data = request.get_json()
    except Exception as e:
        logger.error(f"解析JSON数据失败: {str(e)}")
        return bad_request('Invalid JSON data')
    
    if not data:
        logger.warning("请求中没有提供数据")
        return bad_request('No data provided')
    
    required_fields = ['name', 'bundle_id', 'apple_id', 'username']
    
    # 验证必填字段
    for field in required_fields:
        if field not in data:
            logger.warning(f"缺少必填字段: {field}")
            return bad_request(f'Missing required field: {field}')
        if not data[field]:
            logger.warning(f"字段值为空: {field}")
            return bad_request(f'Field cannot be empty: {field}')
    
    # 验证 bundle_id 格式
    if not data['bundle_id'].count('.') >= 2:
        logger.warning(f"无效的bundle_id格式: {data['bundle_id']}")
        return bad_request('Invalid bundle_id format. Must be in reverse domain format (e.g., com.company.app)')
    
    # 验证 bundle_id 唯一性
    if Project.query.filter_by(bundle_id=data['bundle_id']).first():
        logger.warning(f"bundle_id已存在: {data['bundle_id']}")
        return bad_request('Bundle ID already exists')
    
    try:
        logger.info("开始创建项目")
        project = Project()
        project.from_dict(data, partial=False)
        db.session.add(project)
        db.session.commit()
        logger.info(f"项目创建成功: {project.id}")
        
        response = jsonify(project.to_dict())
        response.status_code = 201
        return response
    except ValueError as e:
        logger.error(f"项目创建失败 - 验证错误: {str(e)}")
        return bad_request(str(e))
    except Exception as e:
        logger.error(f"项目创建失败 - 未知错误: {str(e)}", exc_info=True)
        db.session.rollback()
        return bad_request(f'Error creating project: {str(e)}')

@api.route('/projects/<int:id>', methods=['PUT'])
@log_api_call
def update_project(id):
    """更新项目信息"""
    logger.info(f"开始处理更新项目请求: {id}")
    
    project = Project.query.get_or_404(id)
    logger.info(f"找到项目: {project.name}")
    
    if not request.is_json:
        logger.warning("请求Content-Type不是application/json")
        return bad_request('Content-Type must be application/json')
    
    try:
        data = request.get_json()
    except Exception as e:
        logger.error(f"解析JSON数据失败: {str(e)}")
        return bad_request('Invalid JSON data')
    
    if not data:
        logger.warning("请求中没有提供数据")
        return bad_request('No data provided')
    
    # 验证 bundle_id 唯一性
    if 'bundle_id' in data and data['bundle_id'] != project.bundle_id:
        if Project.query.filter_by(bundle_id=data['bundle_id']).first():
            logger.warning(f"bundle_id已存在: {data['bundle_id']}")
            return bad_request('Bundle ID already exists')
    
    try:
        logger.info("开始更新项目")
        project.from_dict(data, partial=True)
        db.session.commit()
        logger.info(f"项目更新成功: {project.id}")
        return jsonify(project.to_dict())
    except ValueError as e:
        logger.error(f"项目更新失败 - 验证错误: {str(e)}")
        return bad_request(str(e))
    except Exception as e:
        logger.error(f"项目更新失败 - 未知错误: {str(e)}", exc_info=True)
        db.session.rollback()
        return bad_request(f'Error updating project: {str(e)}')

@api.route('/projects/<int:id>', methods=['DELETE'])
@log_api_call
def delete_project(id):
    """删除项目"""
    logger.info(f"开始处理删除项目请求: {id}")
    
    project = Project.query.get_or_404(id)
    logger.info(f"找到项目: {project.name}")
    
    try:
        logger.info("开始删除项目")
        db.session.delete(project)
        db.session.commit()
        logger.info(f"项目删除成功: {id}")
        return '', 204
    except Exception as e:
        logger.error(f"项目删除失败: {str(e)}", exc_info=True)
        db.session.rollback()
        return bad_request(f'Error deleting project: {str(e)}')

@api.route('/projects/<int:id>/versions', methods=['GET'])
@log_api_call
def get_project_versions(id):
    """获取项目版本列表"""
    logger.info(f"获取项目版本列表: {id}")
    
    project = Project.query.get_or_404(id)
    logger.info(f"找到项目: {project.name}")
    logger.info(f"版本数量: {len(project.versions)}")
    
    return jsonify([version.to_dict() for version in project.versions])
